package com.xuanzheng.company.servlet;

import com.google.gson.Gson;
import com.xuanzheng.company.entity.User;
import com.xuanzheng.company.service.UserService;
import com.xuanzheng.company.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/admin/login")
public class AdminLoginServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();
    private Gson gson = new Gson();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求和响应的字符编码
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");
        
        // 获取请求参数
        String adminId = req.getParameter("adminId");
        String password = req.getParameter("password");
        
        // 响应结果
        Map<String, Object> result = new HashMap<>();
        
        // 调用管理员登录服务
        boolean success = userService.adminLogin(adminId, password);
        
        if (success) {
            // 登录成功，将管理员信息保存到session
            HttpSession session = req.getSession();
            
            // 创建一个User对象来表示管理员
            User adminUser = new User();
            adminUser.setId("admin_" + adminId);
            adminUser.setName("系统管理员");
            adminUser.setRole(2); // 角色值为2表示系统管理员
            
            // 保存到session的user属性中
            session.setAttribute("user", adminUser);
            
            // 同时也保留原来的属性，以便向下兼容
            session.setAttribute("admin", adminId);
            session.setAttribute("adminId", adminId);
            session.setAttribute("adminRole", 2);
            
            result.put("success", true);
            result.put("message", "管理员登录成功");
            result.put("redirect", "admin_home.html");
        } else {
            result.put("success", false);
            result.put("message", "管理员账号或密码错误");
        }
        
        // 输出JSON响应
        PrintWriter out = resp.getWriter();
        out.write(gson.toJson(result));
        out.flush();
        out.close();
    }
} 